<?php
namespace app\mobile\controller;

use think\Db;
use think\Url;
use think\Session;
use think\Request;
use think\Response;
use think\Exception;
use app\mobile\model\Shop;
use app\mobile\model\Area;
use app\mobile\model\Image;
use app\mobile\model\Config;
use app\mobile\model\Member;
use app\mobile\model\Feedback;
use app\mobile\model\ShopGoods;
use app\mobile\model\MemberSign;
use app\mobile\model\MemberOrder;
use app\mobile\model\MemberPacket;
use app\mobile\model\MemberBrowse;
use app\mobile\model\LotteryCode;
use app\mobile\model\MemberCollect;
use app\mobile\model\MemberCoupon;
use app\mobile\model\FeedbackType;
use app\mobile\model\MemberAddress;
use app\mobile\model\IntegralGoods;
use app\mobile\model\MemberMessage;
use app\mobile\model\IntegralRecord;
use app\mobile\model\MemberWithdraw;
use app\mobile\model\CashWithdrawal;
use app\mobile\model\MemberBrokerage;
use app\mobile\model\MemberIntegral;
use app\mobile\model\MemberDistribution;
use app\mobile\model\MemberDistributionOrder;
use app\mobile\model\MemberGrade as MemberGradeModel;
use think\Cache;

/**
 * Class UserInfo
 * @package app\mobile\controller    我的信息&设置
 */
class UserInfo extends BaseController
{


    // 前置方法
    protected $beforeActionList = [
        'checkLogin' => ['only' => 'my_shop_index,my_wallet,brokerage_index'],

    ];

    /*
     * 我的店铺主页面
     */
    public function my_shop_index()
    {
        //查找会员资料
        $member_id = Session::get('member_id');

        $memberInfo = (new Member())->where('id', $member_id)->field('id,nickname,avatar,integral,balance,suffer,is_vip')->find();

        // 级别
        $memberInfo['level'] = MemberGradeModel::where(['exp_a' => ['elt', $memberInfo['suffer']], 'exp_b' => ['egt', $memberInfo['suffer']]])->value('name');

        //会员收藏
        $collect = (new MemberCollect())->echo_collect($memberInfo['id']);
        //浏览店铺
        $browse = (new MemberBrowse())->echo_browse($memberInfo['id']);
        //各订单数量
        $orderModel = new MemberOrder();

        // 待付款
        $orderCount['obligation'] = (int)$orderModel->where(['member_id' => $member_id, 'status' => '0'])->count();
        // 代发货
        $orderCount['Shipment'] = (int)$orderModel->where(['member_id' => $member_id, 'status' => '1'])->count();
        // 待收货
        $orderCount['receiving'] = (int)$orderModel->where(['member_id' => $member_id, 'status' => '2'])->count();

        // 待评价
        $orderCount['evaluate'] = (int)$orderModel->where(['member_id' => $member_id, 'status' => '3'])->count();

        // 退换货
        $orderCount['exchange'] = (int)$orderModel->where(['member_id' => $member_id, 'status' => ['in', '6,9,10,11']])->count();

        // 佣金
        $memberInfo['brokerge'] = (int)MemberBrokerage::where('member_id', $member_id)->value('actual_amount');

        // 优惠券
        $memberInfo['coupon'] = (int)MemberCoupon::where(['status' => 2, 'end_time' => ['egt', time()], 'member_id' => $member_id])->count();

        // 红包
        $memberInfo['red'] = (int)MemberPacket::where(['status' => 2, 'end_time' => ['egt', time()], 'member_id' => $member_id])->count();

        // 客服热线
        $tel = Config::where('varname', 'web_customer_service')->value('varvalue');

        return $this->fetch('', [

            'memberInfo' => $memberInfo,
            'collect'    => $collect,
            'browse'     => $browse,
            'orderCount' => $orderCount,
            'tel'        => $tel,
        ]);
    }

    /*
     * 个人资料
     */
    public function self_information()
    {
        if (!Session::has('member_id')) {
            fail('登录异常,请重新登录');
        }
        //查找个人资料
        $arr = (new Member())
            ->where('id', Session::get('member_id'))
            ->field('id,avatar,nickname,sex')
            ->find();

        return $this->fetch('', [
            'arr' => $arr,
        ]);
    }


    public function self_information1()
    {
        if (!Session::has('member_id')) {
            fail('登录异常,请重新登录');
        }
        //查找个人资料
        $arr = (new Member())
            ->where('id', Session::get('member_id'))
            ->field('id,avatar,nickname,sex')
            ->find();

        return $this->fetch('', [
            'arr' => $arr,
        ]);
    }

    /*
     * 修改性别
     */
    public function edit_sex()
    {
        if (Request::instance()->isPost()) {
            $sex = Request::instance()->post('sex');
            $type['sex'] = 1;
            if ($sex == '女') {
                $type['sex'] = 2;
            }
            $res = (new Member())->where('id', Session::get('member_id'))->update($type);
            return $res || $res === 0 ? ['code' => 200, 'message' => '修改成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }

    /*
     * 上传头像
     */
    public function upload_avatar(Request $request)
    {
        if ($request->isPost()) {

            // $mm = $_FILES['file']['size'];

            $path = (new Image())->one_img_upload('file', 'avatar');

            $result = (new Member())->where('id', Session::get('member_id'))->update(['avatar' => $path]);

            return $path && $result ? ['code' => 200, 'message' => $path] : ['code' => 0, 'message' => '上传头像失败'];
        }
    }

    /*
     *
     * 修改昵称
     */
    public function edit_nickname()
    {
        if (Request::instance()->isPost()) {
            $nickname = Request::instance()->post('nickname');
            $nick_len = count(explode(' ',$nickname));
            if($nick_len > 0) return ['code' => 0, 'message' => '名称内不能含有空格'];
            $IntegralRecordModel = new IntegralRecord();
            Db::startTrans();

            try {
                (new Member())->where('id', Session::get('member_id'))->update(['nickname' => $nickname]);

                //检测用户是否首次修改昵称
                // $find = $IntegralRecordModel->where(['member_id' => Session::get('member_id'), 'type' => '编辑昵称'])->find();

                $message = '修改成功';
                 if (!$find){   //首次编辑昵称
                     (new Member())->where('id',Session::get('member_id'))->setInc('integral',Cache::get('web_integral_nickname'));
                     //添加记录
                     $IntegralRecordModel
                         ->isUpdate(false)
                         ->save([
                             'member_id' => Session::get('member_id'),
                             'type_id' => 1,
                             'type' => '编辑昵称',
                             'integral' => Cache::get('web_integral_nickname'),
                             'title' => '（首次）编辑昵称',
                             'create_time' => time(),
                         ]);
                     $message = '修改成功,首次编辑昵称,积分+'.Cache::get('web_integral_nickname');
                 }

                Db::commit();
                return ['code' => 200, 'message' => $message];
            } catch (\Exception $e) {
                Db::rollback();
                return ['code' => 0, 'message' => '网络繁忙,请重试'];
            }
        }
        return $this->fetch('');
    }

    /*
     * 管理收货地址
     */
    public function address_manage()
    {

        $data = (new Member())->where('id', Session::get('member_id'))->field('id,nickname')
            ->with(['memberAddress' => function ($e) {
                $e->order('status asc');
            }])->find();


        return $this->fetch('', [
            'data' => $data,
        ]);
    }

    /*
     * 修改会员收货地址
     */
    public function edit_address(Request $request, $id = '')
    {
        $model = new MemberAddress();
        $areaModel = new Area();
        $arr = MemberAddress::where('id', $id)->find();
        //计算出当前地址的一级地区id
        $two = $areaModel->where('area_id', $arr['area_id'])->value('area_parent_id');
        $one = $areaModel->where('area_id', $two)->value('area_parent_id');
        //所在地区(一级)
        $area = (new Area())
            ->where('area_parent_id', 0)
            ->order('area_sort desc')
            ->field('area_id,area_name')
            ->select();
        if ($request->isPost()) {
            $data = $request->post();
            $data['member_id'] = Session::get('member_id');
            $data['create_time'] = time();
            //查找省市区名称
            $area_info = Area::where('area_id', 'in', $data['province_id'] . ',' . $data['city_id'] . ',' . $data['area_id'])->column('area_name');
            $data['area_info'] = implode(' ', $area_info);
            if ($request->has('status', 'post')) {  //开启默认

                $data['status'] = 1;
                $model->where(['member_id' => Session::get('member_id'), 'status' => 1])->update(['status' => 0]);
                $res = $model->isUpdate(true)->allowField(true)->save($data, ['id' => $data['id']]);
                return $res || $res === 0 ? ['code' => 200, 'message' => '修改成功'] : ['code' => 0, 'message' => '网络繁忙,请重试111'];
            } else {

                $res = $model->isUpdate(true)->allowField(true)->save($data);
                return $res || $res === 0 ? ['code' => 200, 'message' => '修改成功'] : ['code' => 0, 'message' => '网络繁忙,请重试222'];
            }
        }
        return $this->fetch('', [
            'arr'  => $arr,
            'area' => $area,
            'two'  => $two,
            'one'  => $one,
        ]);
    }

    /*
     * 添加会员收货地址
     */
    public function create_address(Request $request)
    {
        // 实例化
        $model = new MemberAddress();
        $area_model = new Area();
        //所在地区(一级)
        $area = $area_model->where('area_parent_id', 0)->order('area_sort desc')->field('area_id,area_name')->select();

        if ($request->isPost()) {
            // 获取数据
            $data = $request->post();
            $data['member_id'] = Session::get('member_id');
            $data['create_time'] = time();

            //查找省市区名称
            $area_info = $area_model->where('area_id', 'in', $data['province_id'] . ',' . $data['city_id'] . ',' . $data['area_id'])->column('area_name');
            $data['area_info'] = implode(' ', $area_info);
            $data['template_id'] = $data['city_id'];

            //会员是否含有地址
            $addressArr = $model->where(['member_id' => Session::get('member_id')])->select();
            if ($addressArr) {
                if ($request->has('status', 'post')) {
                    $data['status'] = 1;
                    $res_update = $model->where(['member_id' => Session::get('member_id'), 'status' => 1])->update(['status' => 0]);
                    $res_create = $model->isUpdate(false)->allowField(true)->save($data);
                    return ($res_create && $res_update) ? ['code' => 200, 'message' => '添加成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
                } else {
                    $data['status'] = 0;
                    $res = $model->isUpdate(false)->allowField(true)->save($data);
                    return $res ? ['code' => 200, 'message' => '添加成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
                }
            } else {   //设为默认
                $data['status'] = 1;
                $res = $model->isUpdate(false)->allowField(true)->save($data);
                return $res ? ['code' => 200, 'message' => '添加成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
            }
        }
        return $this->fetch('', [
            'area' => $area,
        ]);
    }

    /*
     * 城市三级联动
     */
    public function lianDong(Request $request)
    {
        if ($request->isPost()) {
            $id = $request->post('id');  //上级城市id
            $area = (new Area())
                ->where('area_parent_id', $id)
                ->field('area_id,area_name')
                ->order('area_sort desc')
                ->select();
            return $area;
        }
    }

    /*
     * 修改会员默认地址
     */
    public function edit_default()
    {
        $model = new MemberAddress();

        if (Request::instance()->isPost()) {
            $id = Request::instance()->post('id'); //选择的id
            $ids = Request::instance()->post('ids');  //未选中的id
            $ini = ['id' => $id, 'status' => 1];
            $map[] = $ini;
            if ($ids) {
                foreach (explode(',', $ids) as $v) {
                    $map[] = ['id' => $v, 'status' => 2];
                }
            }
            $res = $model->isUpdate(true)->saveAll($map, true);
            return $res ? ['code' => 200, 'message' => '设置成功'] : ['code' => 0, 'message' => '设置失败'];
        }
    }

    /*
     * 删除会员地址
     */
    public function address_del(Request $request)
    {
        if ($request->isPost()) {
            $res = MemberAddress::destroy($request->post('id'));  //删除会员收货地址
            //查看此会员的地址状态
            $arr = MemberAddress::where('member_id', Session::get('member_id'))->field('id,status')->select();
            $change = 1;
            if ($arr) {
                $opt = [];
                foreach ($arr as $v) {
                    $opt[] = $v['status'];
                }
                if (!in_array('1', $opt)) {    //如果会员没有默认地址,将下一个收货地址更改为默认
                    $change = MemberAddress::where('id', reset($arr)['id'])->update(['status' => 1]);
                }
            }
            return $res && $change ? ['code' => 200, 'message' => '删除成功'] : ['code' => 0, 'message' => '删除失败'];
        }
    }

    /*
     * 用户设置首页
     */
    public function user_set_index()
    {
        return $this->fetch('');
    }

    /*
     * 用户退出登录操作
     */
    public function quit_account()
    {
        if (Request::instance()->isPost()) {
            if (Session::has('member_id')) {
                Session::delete('member_id');
                return ['code' => 200, 'message' => '成功退出登录'];
            } else {
                return ['code' => 0, 'message' => '退出失败'];
            }
        }
    }

    /*
     * 账号安全页面
     */
    public function user_account_safety()
    {
        //查看用户是否绑定过手机号
        $bind = Member::where('id', Session::get('member_id'))->value('username');
        return $this->fetch('', [
            'bind' => $bind,
        ]);
    }

    /*
     * 修改登录密码
     */
    public function user_edit_pwd()
    {
        if (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            $model = new Member();
            //查找用户账户信息
            $userInfo = $model->where(['id' => Session::get('member_id'), 'password' => md5(md5($data['old_pwd']))])
                ->find();
            if ($userInfo) {
                //修改密码
                if (stristr(trim($data['new_pwd']), ' ')) {
                    return ['code' => 0, 'message' => '新密码输入格式不正确'];
                }
                if ($data['new_pwd'] != $data['confirm_new_pwd']) {
                    return ['code' => 0, 'message' => '两次密码输入不正确'];
                };
                if ($data['new_pwd'] === $data['old_pwd']) {
                    return ['code' => 0, 'message' => '新密码不能与旧密码一致'];
                }
                $res = $model->isUpdate(true)->where('id', $userInfo['id'])->update(['password' => md5(md5(trim($data['new_pwd'])))]);
                if ($res) {
                    Session::delete('member_id');
                    return ['code' => 200, 'message' => '修改成功'];
                }
                return ['code' => 0, 'message' => '修改失败'];
            } else {
                return ['code' => 0, 'message' => '原密码不正确!'];
            }
        }
        return $this->fetch('');
    }

    /*
     * 修改绑定手机
     */
    public function edit_bind_phone()
    {
        //查看用户是否绑定过手机号
        $bind = Member::where('id', Session::get('member_id'))->value('username');
        return $this->fetch('', [
            'bind' => $bind,
        ]);
    }

    /*
     * 绑定小号手机号
     */
    public function bind_small_phone()
    {
        return $this->fetch('');
    }

    /*
     * 新消息通知
     */
    public function msg_tip_set()
    {
        return $this->fetch('');
    }

    /*
     * 关于我们
     */
    public function user_about_us()
    {
        return $this->fetch('');
    }

    /*
     * 意见和反馈
     */
    public function idea_feedback(Request $request)
    {
        //反馈类型
        $type = FeedbackType::where('status', 1)->order(['sort' => 'desc', 'update_time' => 'desc'])->select();
        //提交反馈内容
        if ($request->isPost()) {
            $data = $request->post();
            $data['ip'] = $request->ip();
            $data['create_time'] = time();
            $result = (new Feedback())->allowField(true)->save($data);
            return $result ? ['code' => 200, 'message' => '提交成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
        return $this->fetch('', [
            'type' => $type,
        ]);
    }

    /*
     * 会员等级说明(纯展示页)
     */
    public function member_level()
    {
        return $this->fetch('');
    }

    /*
     * 会员等级主页
     */
    // public function member_level_index()
    // {
    //     //查找会员经验
    //     $suffer = (new Member())
    //         ->where('id', Session::get('member_id'))
    //         ->value('suffer');
    //     //经验对照表
    //     $sufferArr = (new MemberGrade())
    //         ->where('exp_a', 'elt', $suffer)
    //         ->where('exp_b', 'egt', $suffer)
    //         ->field('name,picUrl')
    //         ->find();
    //     return $this->fetch('', [
    //         'suffer' => $suffer,
    //         'sufferArr' => $sufferArr,
    //     ]);
    // }

    /*
     *收藏商品 / 店铺
     */
    public function my_collect(Request $request)
    {
        if ($request->isPost()) {
            $type = $request->post('type', 1);
            $page = $request->post('page');
            $model = new MemberCollect();
            $condition = [
                'sun_member_collect.type_id'   => $type,
                'sun_member_collect.member_id' => Session::get('member_id'),
            ];
            if ($type == 1) {   //商品
                $data['data'] = $model
                    ->where($condition)
                    ->with('shopGoods')
                    ->limit(($page - 1) * 10, 10)
                    ->select();

                $data['pages'] = ceil($model->where('type_id', 1)
                        ->where('member_id', Session::get('member_id'))
                        ->count() / 10);
                return $data;
            } else {  //店铺
                $data['data'] = $model
                    ->where($condition)
                    ->with(['shop' => function ($e) {
                        $e
                            ->withField('member_id,title,collect_number,logo');
                    }])
                    ->limit(($page - 1) * 10, 10)
                    ->select();
                $data['pages'] = ceil($model->where('type_id', 2)
                        ->where('member_id', Session::get('member_id'))
                        ->count() / 10);
                return $data;
            }
        }
        return $this->fetch('');
    }

    /*
     * 删除收藏
     */
    public function del_collect(Request $request)
    {
        if ($request->isPost()) {
            $id = $request->post('id');

            //查找收藏的店铺||商品id
            $idArr = MemberCollect::where('id', 'in', $id)->column('collect_id');

            $del = MemberCollect::destroy($id);

            $type = $request->post('type');
            if ($type == 2) {
                //减少店铺收藏数
                $dec = (new Shop())
                    ->where('member_id', 'in', implode(',', $idArr))
                    ->setDec('collect_number');
            } else {
                //减少商品收藏量
                $dec = (new ShopGoods())
                    ->where('id', 'in', implode(',', $idArr))
                    ->setDec('collect');
            }
            return $del && $dec ? ['code' => 200, 'message' => '删除成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }

    /*
     * 浏览店铺
     */
    public function shop_browse(Request $request)
    {
        if ($request->isPost()) {
            $page = $request->post('page', 1);
            $result['data'] = Db::view('member_browse', 'id,member_id,goods_id,create_time')
                ->view('shop_goods', 'sale_number,title,price,thumb_img,rebate_percentage', 'shop_goods.id = member_browse.goods_id')
                ->where(['member_id' => Session::get('member_id')])
                ->order(['create_time' => 'desc'])
                ->limit(($page - 1) * 20, 20)
                ->select();
            $arr = [];
            foreach ($result['data'] as &$v) {
                $arr['data'][$v['create_time']][] = $v;
            }

            $arr['pages'] = ceil((new MemberBrowse())
                    ->where('sun_member_browse.member_id', Session::get('member_id'))
                    ->with('shopGoods')
                    ->count() / 20);
            return $arr;
        }
        return $this->fetch('');
    }

    /*
     * 清空记录
     */
    public function empty_browse()
    {
        if (Request::instance()->isPost()) {

            $res = (new MemberBrowse())->where('member_id', Session::get('member_id'))->delete();

            return $res ? ['code' => 200, 'message' => '清空成功'] : ['code' => 0, 'message' => '清空成功'];

        }
    }

    /*
     * 删除记录
     */
    public function del_browse()
    {
        if (Request::instance()->isPost()) {
            $id = Request::instance()->post('id');
            $res = MemberBrowse::destroy($id);
            return $res ? ['code' => 200, 'message' => '删除成功'] : ['code' => 0, 'message' => '网络繁忙,请重试'];
        }
    }

    /*
     * 我的订单
     */
    public function member_order(Request $request)
    {
        if ($request->isPost()) {
            // 获取参数
            $status = $request->param('status', 'all');
            $page = $request->param('page');
            $title = $request->param('title');
            // 搜索条件
            $condition['sun_member_order.member_id'] = ['eq', Session::get('member_id')];

            // 条件
            if ($status == 'all' || !$status) $condition['sun_member_order.status'] = ['neq', '5'];  //取消订单
            if ($status <> 'all') $condition['sun_member_order.status'] = ['in', $status];
            // if (!empty($request->param('title'))) $condition['sun_member_order.order_number'] = $request->param('title');

            $model = new MemberOrder();

            $allData = $model->where($condition)->relation(['shop', 'memberOrderAttached'])->order('create_time desc')->select();
            // return json($allData);

            if ($title) {

                $findShopArr = $model->where($condition)->with(['shop' => function ($query) use ($title) {

                    $query->where(['title' => ['like', '%' . $title . '%']]);
                }])->select();

                $findShop = [];
                foreach ($findShopArr as $value) {
                    if ($value->shop) {
                        $findShop[] = $value->id;
                    }
                }

                //模糊查询附表商品标题

                $findGoods = $model->where($condition)
                    ->with(['memberOrderAttached' => function ($e) use ($title) {
                        $e->where(['title' => ['like', '%' . $title . '%']]);
                    }])
                    ->select();

                $findGoodsId = [];
                foreach ($findGoods as $item) {

                    if (count($item['member_order_attached']) > 0) {
                        $findGoodsId[] = $item->id;
                    }
                }

                $merge = [];
                if ($findShop && $findGoodsId) {
                    foreach ($findShop as &$item) {
                        if (in_array($item, $findGoodsId)) {
                            unset($item);
                        }
                    }
                    $merge = array_merge($findGoodsId, $findShop);
                } elseif ($findGoodsId && !$findShop) {
                    $merge = $findGoodsId;
                } elseif (!$findGoodsId && $findShop) {
                    $merge = $findShop;
                }


                $allData = $model->where($condition)->where(['id' => ['in', implode(',', $merge)]])->relation(['shop', 'memberOrderAttached'])->order('create_time desc')->select();

            }

            if ($allData) {
                foreach ($allData as $key => &$value) {
                    $value->total_num = 0;
                    $value->pay_money = 0;
                    if ($value['memberOrderAttached']) {
                        foreach ($value['memberOrderAttached'] as $item) {
                            $value->total_num += $item['number'];
                        }
                    } else {
                        unset($allData[$key]);   //查询专用
                    }
                    $value->pay_money = $value->price;
                }
            }
            $result['data'] = array_slice($allData, ($page - 1) * 5, 5);
            $result['pages'] = ceil(count($allData) / 5);
            return $result;
        }

        return $this->fetch('');
    }


    // 订单搜索页面
    public function search_member_order(Request $request)
    {
        $model = new MemberOrder();

        if ($request->isPost()) {
            $condition['sun_member_order.member_id'] = ['eq', Session::get('member_id')];
            $title = $request->param('title');
            $page = $request->param('page');

            $allData = $model->where($condition)->relation(['shop', 'memberOrderAttached'])->order('create_time desc')->select();
            // return json($allData);

            if ($title) {

                $findShopArr = $model->where($condition)->with(['shop' => function ($query) use ($title) {

                    $query->where(['title' => ['like', '%' . $title . '%']]);
                }])->select();

                $findShop = [];
                foreach ($findShopArr as $value) {
                    if ($value->shop) {
                        $findShop[] = $value->id;
                    }
                }

                //模糊查询附表商品标题

                $findGoods = $model->where($condition)
                    ->with(['memberOrderAttached' => function ($e) use ($title) {
                        $e->where(['title' => ['like', '%' . $title . '%']]);
                    }])
                    ->select();

                $findGoodsId = [];
                foreach ($findGoods as $item) {

                    if (count($item['member_order_attached']) > 0) {
                        $findGoodsId[] = $item->id;
                    }
                }

                $merge = [];
                if ($findShop && $findGoodsId) {
                    foreach ($findShop as &$item) {
                        if (in_array($item, $findGoodsId)) {
                            unset($item);
                        }
                    }
                    $merge = array_merge($findGoodsId, $findShop);
                } elseif ($findGoodsId && !$findShop) {
                    $merge = $findGoodsId;
                } elseif (!$findGoodsId && $findShop) {
                    $merge = $findShop;
                }


                $allData = $model->where($condition)->where(['id' => ['in', implode(',', $merge)]])->relation(['shop', 'memberOrderAttached'])->order('create_time desc')->select();

            }

            if ($allData) {
                foreach ($allData as $key => &$value) {
                    $value->total_num = 0;
                    $value->pay_money = 0;
                    if ($value['memberOrderAttached']) {
                        foreach ($value['memberOrderAttached'] as $item) {
                            $value->total_num += $item['number'];
                        }
                    } else {
                        unset($allData[$key]);   //查询专用
                    }
                    $value->pay_money = $value->price;
                }
            }
            $result['data'] = array_slice($allData, ($page - 1) * 5, 5);
            $result['pages'] = ceil(count($allData) / 5);
            return $result;
        }

        return $this->fetch('');
    }



    /*
     * 订单专用数组分组
     *
     * @param object $data 二维数组
     * @param object $obj 对象
     */
    protected function cartGrouping($data, $val, $title, $list, $val2, $title2)
    {
        $result = array_values(array_reduce($data, function ($value, $key) use ($val, $val2, $title, $title2, $list) {
            $name = $key[$val];
            $name2 = $key[$val2];
            unset($key[$val]);
            $value[$name][$title] = $name;
            $value[$name][$title2] = $name2;
            $value[$name][$list][] = $key;
            return $value;
        }));

        return $result;
    }

    /*
     * 用户订单查询
     */
    public function member_order_search()
    {
        return $this->fetch('');
    }

    /*
     * 订单详情
     */
    public function member_order_details()
    {
        $order_id = Request::instance()->param('order_id');
        $data = (new MemberOrder())
            ->where('id', $order_id)
            ->with('memberOrderAttached')
            ->find();
        $data->shop;
        $data->member;

        return $this->fetch('', [
            'data' => $data,
        ]);
    }

    /*
     * 图片上传
     * @param string $img 图片名称
     */
    public function uploadImg()
    {
        $file = request()->file('file');

        if (!empty($file)) {

            // 移动到框架应用根目录/public/uploads/ 目录下
            $upload = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            if ($upload) {

                //返回图片地址Response
                return Response::create(['picUrl' => 'uploads/' . date('Ymd') . '/' . $upload->getFilename()], 'json', 200);
            }

            return $file->getError();
        }

    }

    /*
     * 图片删除
     * @param string $img 图片名称
     */
    public function uploadImgDestroy()
    {
        $picUrl = Request::instance()->param('picUrl');

        if (!empty($picUrl)) {

            unlink($picUrl);
            return ['code' => 200, 'message' => '取消成功'];

        }

        return ['code' => 400, 'message' => '网络繁忙'];
    }


    // 我的钱包主页
    public function my_wallet()
    {
        // 实例化
        $member_model = new Member();
        $member_brokerage = new MemberBrokerage();
        $member_id = Session::get('member_id');

        // 用户之前余额
        $amount = $member_model->where('id',$member_id)->value('balance');

        //查看当前用户是否设置过支付密码
        $info = $member_model->where('id', $member_id)->find();

        //佣金余额
        $brokerage  = $member_brokerage->where('member_id',$member_id)->value('actual_amount');


        return $this->fetch('', [
            'info'   => $info,
            'amount' => $amount,
            'brokerage' => $brokerage,
        ]);
    }

    /*
     * 钱包明细
     */
    public function wallet_details()
    {
        if (Request::instance()->isPost()) {
            // 搜索条件
            $model = new MemberWithdraw();
            $condition = (Request::instance()->post('type', 0) == 0) ? [] : ['type_id' => Request::instance()->post('type')];
            $page = Request::instance()->post('page');
            $result['data'] = $model
                ->where(['member_id' => Session::get('member_id'), 'status' => 1])
                ->field('id,type_id,price,balance,create_time')
                ->where($condition)
                ->order('create_time desc')
                ->limit(($page - 1) * 10, 10)
                ->select();
            $result['data'] = array_map(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            }, $result['data']);
            $result['pages'] = ceil($model
                    ->where(['member_id' => Session::get('member_id'), 'status' => 1])
                    ->where($condition)
                    ->count() / 10);
            return $result;
        }
        return $this->fetch('');
    }

    /*
     * 充值首页
     */
    public function recharge_index()
    {
        //当前余额
        $amount = MemberBrokerage::where(['member_id' => Session::get('member_id')])->value('actual_amount');
        return $this->fetch('', [
            'amount' => $amount,
        ]);
    }

    /*
     * 充值处理
     */
    public function recharge()
    {
        // 用户之前余额
        $amount = Member::where(['id' => Session::get('member_id')])->value('balance');

        // 生成订单号
        $order_number = $this->createNumber();
        // 展示数据
        $model = new MemberWithdraw();
        $price = Request::instance()->post('price');
        $way = Request::instance()->post('way');
        $information = [
            'type_id'      => '1',
            'member_id'    => Session::get('member_id'),
            'balance'      => ($amount + $price),
            'price'        => $price,
            'way'          => $way,
            'status'       => '3',
            'order_number' => $order_number,
            'create_time'  => time()
        ];

        // 添加成功
        $result = $model->save($information);
        return $result ? ['code' => 200] : ['code' => 0];
    }

    /*
     * 提现首页
     */
    public function withdraw_index()
    {
        $member_id = Session::get('member_id');
        $find = (new Member())->where('id', $member_id)->find();

        if (Request::instance()->isPost()) {
            $cash = Request::instance()->param('cash');
            $card = Request::instance()->param('card');
            $bank = Request::instance()->param('bank');
            $real_name = Request::instance()->param('real_name');
            Db::startTrans();

            try {
                $ini = [
                    'member_id'    => $member_id,
                    'type_id'      => 2,
                    'price'        => $cash,
                    'way'          => '提现',
                    'name'         => $bank,
                    'real_name'    => $real_name,
                    'account'      => $card,
                    'status'       => 3,
                    'reason'       => '',
                    'create_time'  => time(),
                    'order_number' => self::createNumber()
                ];

                Db::name('member_withdraw')->insert($ini);
                Db::name('member')->where('id', $member_id)->setDec('balance', $cash);
                Db::name('member_brokerage')->where('member_id', $member_id)->setInc('to_audit', $cash);
                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '提现申请成功'];
            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙,请重试'];
            }
        }

        return $this->fetch('', [
            'balance' => $find['balance']
        ]);
    }

    /*
     * 生成订单号码
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }

    /*
     * 佣金首页
     */
    public function brokerage_index()
    {
        $model = new MemberBrokerage();
        $result = $model->where(['member_id' => Session::get('member_id')])->field('member_id', true)->find();

        //查看用户当前层级 (用于查找下2级分润会员)
        $level = MemberDistribution::where('referrals_id', Session::get('member_id'))->value('level');

        // 分销商人总数 (自己下两级)
        $result['distribution'] = MemberDistribution::where([
            'hierarchy' => ['like', '%,' . Session::get('member_id') . ',%'],
            'level'     => ['elt', $level + 2]
        ])->count();


        //查找分销会员id
        $result['distribution_ids'] = MemberDistribution::where([
            'hierarchy' => ['like', '%' . Session::get('member_id') . '%'],
            'level'     => ['elt', ($level + 2)],   //只查下两级
        ])->column('referrals_id');

        $result['distribution_order_count'] = 0;

        //所有下2级分销商
        $data = (new MemberDistribution())
            ->where([
                'sun_member_distribution.level'     => ['elt', ($level + 2)],   //只查下两级
                'sun_member_distribution.hierarchy' => ['like', '%,' . Session::get('member_id') . ',%']
            ])
            ->with([
                'member',
                'memberDistributionOrder' => function ($e) {
                    $e
                        ->where('distribution_id', Session::get('member_id'));  //分销订单上级会员id是当前会员
                }
            ])
            ->order(['create_time' => 'desc'])
            ->select();
        //去除没有会员信息和分销订单的数据
        $num = 0;
        if ($data) {
            foreach ($data as $key => &$item) {
                if (!$item['member'] || !$item['member_distribution_order']) {
                    unset($data[$key]);
                } else {
                    foreach ($item['member_distribution_order'] as $o) {
                        $o->memberOrder;    //分销订单关联会员已产生佣金的订单[状态为3,4]
                    }
                    foreach ($item['member_distribution_order'] as $_key => $_item) {
                        if (!is_null($_item['memberOrder'])) {
                            $num++;
                        }
                    }
                }
            }
        }

        //分销会员已产生佣金的订单数量 (按店铺计)
        $result['distribution_order_count'] = $num;

        //从分销会员那里收入的佣金
        $distribution_brokerage = (new MemberDistributionOrder())
            ->where([
                'sun_member_distribution_order.member_id'       => ['in', implode(',', $result['distribution_ids'])],
                'sun_member_distribution_order.distribution_id' => Session::get('member_id'),
            ])->with(['memberOrder'])->select();

        //        return json($distribution_brokerage);
        $result['distribution_brokerage'] = "0.00";
        $result['distribution_to_yield'] = "0.00";

        if ($distribution_brokerage) {

            foreach ($distribution_brokerage as $value) {

                if ($value->orderBrokerage) {
                    if (in_array($value->orderBrokerage->status, [3, 4])) {  //下级返给本人已收益

                        $result['distribution_brokerage'] = bcadd($result['distribution_brokerage'], $value->brokerage, 2);
                    } else if (in_array($value->orderBrokerage->status, [0, 1, 2])) {  //下级返给本人待收益

                        $result['distribution_to_yield'] = bcadd($result['distribution_to_yield'], $value->brokerage, 2);

                    }
                }
            }
        }

        //本人周周币(自己买的已收益的)
        $result['self_general_income'] = bcsub(bcsub($result['general_income'], $result['to_yield'], 2), $result['distribution_brokerage'], 2);

        //周周币总收入
        $result['total_money'] = bcadd($result['distribution_brokerage'], $result['general_income'], 2);

        //本人待收益合计
        $result['self_to_yield'] = bcsub($result['to_yield'], $result['distribution_to_yield'], 2);

        //待审核合计
        $result['total_to_audit'] = $model->where(
            'member_id', 'in', implode(',', $result['distribution_ids']) . ',' . Session::get('member_id')
        )
            ->sum('to_audit');
        //本人订单的数量
        $self_data = MemberDistribution::where(
            'sun_member_distribution.referrals_id', Session::get('member_id')
        )->with([
            'member',
            'memberDistributionOrder' => function ($e) {
                $e
                    ->where('distribution_id', Session::get('member_id'));  //分销订单上级会员id是当前会员
            }
        ])
            ->select();

        //去除没有会员信息和分销订单的数据
        $self_num = 0;
        if ($self_data) {
            foreach ($self_data as $key => &$item) {

                if (!$item->member || !$item['member_distribution_order']) {
                    unset($self_data[$key]);
                } else {
                    foreach ($item['member_distribution_order'] as $o) {
                        $o->memberOrder;    //分销订单关联会员已产生佣金的订单
                    }
                    foreach ($item['member_distribution_order'] as $_key => $_item) {
                        if (!is_null($_item['memberOrder']) && $_item['brokerage'] != 0) {
                            $self_num++;
                        }
                    }
                }
            }
        }
        $result['self_order'] = $self_num;

        return $this->fetch('', [
            'result' => $result,
        ]);
    }

    /*
     * 佣金明细
     */
    public function brokerage_details(Request $request)
    {
        if ($request->isPost()) {
            $model = new MemberDistributionOrder();
            $page = $request->post('page');
            $type = $request->post('type', 1);
            if ($type == 1) {
                $result['data'] = $model
                    ->where(['distribution_id' => Session::get('member_id')])
                    ->with(['memberOrder' => function ($e) {
                        $e
                            ->where(['status' => ['gt', 2]]);
                    }])
                    ->limit(($page - 1) * 10, 10)
                    ->order('create_time desc')
                    ->select();
            } else {
                $cash = (new CashWithdrawal)->where('member_id', Session::get('member_id'))->limit(($page - 1) * 10, 10)
                    ->order('create_time desc')->select();
                $result['data'] = "";
                foreach ($cash as $value) {
                    if ($value['type_id'] == 1) {
                        $result['data'][] = [
                            'title'       => '佣金提现到余额',
                            'create_time' => date('Y-m-d', $value['create_time']),
                            'brokerage'   => $value['cash']
                        ];
                    } else {
                        $result['data'][] = [
                            'title'       => '佣金提现第三方账户',
                            'create_time' => date('Y-m-d', $value['create_time']),
                            'brokerage'   => $value['cash']
                        ];
                    }

                }
            }

            if ($type == 1) {
                $result['pages'] = ceil($model->where(['distribution_id' => Session::get('member_id')])
                        ->with(['memberOrder' => function ($e) {
                            $e
                                ->where(['status' => ['gt', 2]]);
                        }])->count() / 10);
            } else {
                $result['pages'] = ceil((new CashWithdrawal)->where('member_id', Session::get('member_id'))->count() / 10);
            }
            return $result;
        }
        return $this->fetch('');
    }

    /*
     * 我要提现(佣金)
     */
    public function withdrawals()
    {
        $amount = (new MemberBrokerage())->where(['member_id' => Session::get('member_id')])->value('actual_amount');
        return $this->fetch('', [
            'balance' => $amount,
        ]);
    }

    /*
     * 提现到余额(佣金)
     */
    public function to_balance(Request $request)
    {
        $user_id = Session::get('member_id');
        // 用户之前佣金余额
        $amount = MemberBrokerage::where(['member_id' => $user_id])->value('actual_amount');
        if ($request->isPost()) {
            $cash = $request->post('cash');  //用户提现金额

            // 账号
            $balance = Member::where(['id' => $user_id])->value('balance');

            if ($amount < $cash) return ['code' => 402, 'message' => '余额不足'];

            // 启动事务
            Db::startTrans();
            try {

                // 生成订单号
                $order_number = $this->createNumber();

                $information = [
                    'member_id'   => $user_id,
                    'type_id'     => 1,
                    'way'         => '提现到余额',
                    'account'     => '余额账户',
                    'status'      => 1,
                    'cash'        => $cash,
                    'create_time' => time()
                ];

                $sisn = [
                    'member_id'    => $user_id,
                    'type_id'      => 2,
                    'price'        => $cash,
                    'way'          => '佣金提现到余额',
                    'name'         => '',
                    'real_name'    => '',
                    'account'      => '',
                    'balance'      => $balance + $cash,
                    'status'       => 1,
                    'reason'       => '',
                    'order_number' => $order_number,
                    'create_time'  => time(),
                ];

                // 添加成功
                Db::name('member_withdraw')->insert($sisn);
                Db::name('cash_withdrawal')->insert($information);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('actual_amount', $cash);
                Db::name('member_brokerage')->where(['member_id' => $user_id])->setDec('general_income', $cash);
                Db::name('member')->where(['id' => $user_id])->setInc('balance', $cash);

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '提现成功', 'order_number' => $order_number];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙,请重试'];
            }

        }
        return $this->fetch('', [
            'balance' => $amount,
        ]);
    }

    /*
     * 赚取佣金(分享页)
     */
    public function get_commission()
    {
        return $this->fetch('');
    }

    /*
     * 我的钱包 优惠券
     */
    public function my_coupon_index(Request $request)
    {
        $model = new MemberCoupon();
        $count = self::coupon_num([]);

        if ($request->isPost()) {
            //优惠券原始数据
            $page = $request->post('page');
            $type = $request->post('type');
            $total_price = $request->post('total_price');
            $shop_id = $request->post('shop_id');
            $order = [];
            if ($total_price && $shop_id) {  //筛选符合确认订单的优惠券
                $order = [
                    'sun_member_coupon.virtual_price' => ['elt', $total_price], //虚拟金额<=单店铺合计金额
                    'sun_member_coupon.shop_id'       => ['in', '0,' . $shop_id],   //此店铺或者平台优惠券
                ];
                $data['count'] = self::coupon_num($order);
            }
            //已使用(使用记录)
            $condition = [
                'sun_member_coupon.member_id' => Session::get('member_id'),
                'sun_member_coupon.status'    => 1,
            ];
            if ($type == 3) {  //已过期(反馈优惠券不会过期 , 排除)
                $condition = [
                    'sun_member_coupon.member_id' => Session::get('member_id'),
                    'sun_member_coupon.status'    => 2,
                    'sun_member_coupon.end_time'  => [['lt', time()], ['gt', 0]]];
            }
            if ($type == 2) {  //待使用
                $condition = [
                    'sun_member_coupon.member_id' => Session::get('member_id'),
                    'sun_member_coupon.status'    => 2,
                    'sun_member_coupon.end_time'  => ['notbetween', '1,' . time()]
                ];
            }

            $data['data'] = $model->where($condition)->where($order)->order(['id' => 'desc'])->limit(($page - 1) * 10, 10)
                ->select();
            //            return json($data);
            foreach ($data['data'] as &$v) {
                $v->coupon;
                $v['start_time'] = date('Y-m-d', $v['start_time']);
                $v['end_time'] = date('Y-m-d', $v['end_time']);
            }

            $data['pages'] = ceil($model->where($condition)->where($order)->count() / 10);
            return $data;
        }
        return $this->fetch('', [
            'count' => $count,
        ]);
    }

    /*
     * 优惠券各数量统计
     */
    public function coupon_num($order)
    {
        $model = new MemberCoupon();
        //未使用数量
        $count['not_use'] = $model->with('coupon')
            ->where([
                'sun_member_coupon.member_id' => Session::get('member_id'),
                'sun_member_coupon.status'    => 2,
                'sun_member_coupon.end_time'  => ['notbetween', '1,' . time()]
            ])->count();

        //已使用数量
        $count['used'] = $model->with('coupon')
            ->where([
                'member_id' => Session::get('member_id'),
                'status'    => 1
            ])->count('id');
        //过期数量
        $count['out_time'] = $model->with('coupon')
            ->where([
                'member_id' => Session::get('member_id'),
                'status'    => 2,
                'end_time'  => [['lt', time()], ['gt', 0]]
            ])->count('id');
        return $count;
    }

    /*
     * 优惠券使用规则(纯展示页)
     */
    public function coupon_user_rule()
    {
        return $this->fetch('');
    }

    /*
    * 优惠券使用规则(APP展示页)
    */
    public function app_coupon_rule()
    {
        return $this->fetch('');
    }


    // 佣金说明（APP展示页）
    public function app_commission_rule()
    {
        return $this->fetch('');
    }

    /*
     * 红包
     */
    public function packet(Request $request)
    {
        $model = new MemberPacket();
        $count = self::pack_num([]);

        if ($request->isPost()) {
            $page = $request->post('page');
            $type = $request->post('type');
            $total_price = $request->post('total_price');
            $order = [];
            if ($total_price) {  //筛选符合确认订单的红包
                $order = [
                    'virtual_price' => ['elt', $total_price], //虚拟金额<=订单总计金额
                ];
                $data['count'] = self::pack_num($order);
            }
            $condition = ['member_id' => Session::get('member_id'), 'status' => $type];
            if ($type == 3) {
                $condition = ['member_id' => Session::get('member_id'), 'status' => 2, 'end_time' => ['lt', time()]];
            }
            if ($type == 2) {
                $condition = ['member_id' => Session::get('member_id'), 'status' => 2, 'end_time' => ['gt', time()]];
            }
            $data['data'] = $model
                ->where($condition)
                ->where($order)
                ->field('id,title,actual_price,packet_id,virtual_price,content,start_time,end_time,status')
                ->order(['id' => 'desc'])
                ->limit(($page - 1) * 10, 10)
                ->select();
            foreach ($data['data'] as &$v) {
                $v['start_time'] = date('Y-m-d', $v['start_time']);
                $v['end_time'] = date('Y-m-d', $v['end_time']);
            }
            $data['pages'] = ceil($model
                    ->where($condition)
                    ->where($order)
                    ->count() / 10);
            return $data;
        }
        return $this->fetch('', [
            'count' => $count,
        ]);
    }

    /*
     * 红包统计数量
     */
    public function pack_num($order)
    {
        $model = new MemberPacket();
        $count['not_use'] = $model
            ->where([
                'member_id' => Session::get('member_id'),
                'status'    => 2,
                'end_time'  => ['gt', time()]
            ])
            ->where($order)
            ->count();  //未使用数量
        $count['used'] = $model
            ->where([
                'member_id' => Session::get('member_id'),
                'status'    => 1
            ])
            ->where($order)
            ->count();  //已使用数量
        $count['out_time'] = $model
            ->where([
                'member_id' => Session::get('member_id'),
                'status'    => 2,
                'end_time'  => ['lt', time()]
            ])
            ->where($order)
            ->count();  //过期数量
        return $count;
    }

    /*
     * 红包使用规则(纯展示页)
     */
    public function packet_rule()
    {
        return $this->fetch('');
    }

    /*
     * 积分首页(我的钱包)
     */
    public function integral_index(Request $request)
    {
        // 用户积分
        $integral = Member::where(['id' => Session::get('member_id')])->value('integral');
        //积分商品列表
        if ($request->isPost()) {
            $model = new IntegralGoods();
            $page = $request->post('page');
            // 读取列表
            $data['data'] = $model
                ->field('id,title,number,picUrl,price,market_price')
                ->order(['sort' => 'asc','id' => 'desc'])
                ->limit(($page - 1) * 10, 10)
                ->select();

            foreach ($data['data'] as $value) {
                if ($value['id'] == 1) {
                    $value['number'] = '不限';
                }
            }

            $data['pages'] = ceil($model->count() / 10);
            return $data;
        }
        return $this->fetch('', [
            'integral' => $integral,
        ]);
    }


    // 兑换记录
    public function exchange_record()
    {
        // 实例化
        $model = new MemberIntegral();

        // 筛选
        $condition['member_id'] = ['eq', Session::get('member_id')];

        // 获取数据
        $data = $model->where($condition)->field('id,title,number,picUrl,integral,status,create_time')->order('id','desc')->paginate(10);


        return $this->fetch('', [
            'data' => $data
        ]);
    }

    /*
     * 积分明细
     */
    public function integral_details(Request $request)
    {
        if ($request->isPost()) {
            // 搜索条件
            $condition['member_id'] = ['eq', Session::get('member_id')];
            $page = $request->post('page');
            // 条件
            if ($request->has('type', 'post') && $request->post('type') != 0) $condition['type_id'] = ['eq', $request->post('type')];

            $model = new IntegralRecord();
            // 读取列表
            $data['data'] = $model->where($condition)
                ->field('id,type,title,integral,create_time,type_id')
                ->order(['id' => 'desc'])
                ->limit(($page - 1) * 10, 10)
                ->select();
            $data['pages'] = ceil($model->where($condition)
                    ->count() / 10);
            return $data;
        }
        return $this->fetch('');
    }

    /*
     * 积分兑换
     */
    public function integral_exchange(Request $request)
    {

        $id = $request->get('goods_id');   //积分商品id
        $address_id = $request->get('address_id', '');
        //查找商品详情
        $data = (new IntegralGoods())->where('id', $id)->find();
        //用户默认收货地址
        $address = (new MemberAddress)->where(['member_id' => Session::get('member_id')])->field('name,phone,address,area_info')->find();

        if ($address_id) {
            //选择了新的收获地址
            $address = (new MemberAddress)->where(['id' => $address_id])->field('name,phone,address,area_info')->find();
        }
        //用户积分总额
        $total = (new Member)->where('id', Session::get('member_id'))->value('integral');

        return $this->fetch('', [
            'data'    => $data,
            'address' => $address,
            'total'   => $total,
        ]);
    }

    /*
     *兑换抽奖码
     */
    public function integral_code()
    {
        Db::startTrans();

        try {
            // 生成抽奖码
            $model = new LotteryCode();

            //获取最后一条信息
            $find = $model->max('lottery_code');

            if ($find) {
                $lottery_code = (int)$find + 1;
            } else {
                $lottery_code = 1000001;
            }

            $ini = [
                'lottery_code' => $lottery_code,
                'member_id'    => Session::get('member_id'),
                'type_id'      => 2,
                'create_time'  => time(),
            ];

            $model->save($ini);

            Db::name('member')->where('id', Session::get('member_id'))->setDec('integral', 1);

            Db::name('integral_record')->insert(
                [
                    'member_id'   => Session::get('member_id'),
                    'type_id'     => '2',
                    'type'        => '兑换',
                    'integral'    => 1,
                    'title'       => '兑换' . '抽奖码',
                    'create_time' => time()
                ]
            );

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '取消订单成功'];
        } catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'message' => '网络繁忙,请重试'];
        }


    }

    /*
     * 积分兑换处理
     */
    public function exchange_act(Request $request)
    {
        if ($request->isPost()) {

            // 获取参数
            $data = Request::instance()->post();

            if ($data['area_info'] == '' || $data['address'] == '' || $data['phone'] == '' || $data['name'] == '') {
                return ['code' => 401, 'message' => '请选择收货地址'];
            }
            // 启动事务
            Db::startTrans();
            try {

                // 读取会员积分 和 商品需要积分
                $find = Db::name('member')->where(['id' => Session::get('member_id')])->value('integral');
                $integral = Db::name('integral_goods')->where(['id' => $data['goods_id']])->field('price,number')->find();

                if ($find < $integral['price']) return ['code' => 402, 'message' => '积分不足,无法兑换'];

                if ($integral['number'] < $data['number']) return ['code' => 402, 'message' => '剩余数量不足,无法兑换'];

                $information = [
                    'member_id'   => Session::get('member_id'),
                    'name'        => $data['name'],
                    'phone'       => trim($data['phone']),
                    'area_info'   => $data['area_info'],
                    'address'     => $data['address'],
                    'goods_id'    => $data['goods_id'],
                    'title'       => $data['title'],
                    'number'      => $data['number'],
                    'picUrl'      => $data['picUrl'],
                    'integral'    => $integral['price'],
                    'status'      => '1',
                    'create_time' => time()
                ];

                // 添加
                Db::name('member_integral')->insert($information);

                //扣除积分商品剩余数量
                Db::name('integral_goods')->where(['id' => $data['goods_id']])->setDec('number', $data['number']);

                // 扣除积分
                Db::name('member')->where(['id' => Session::get('member_id')])->setDec('integral', $integral['price'] * $data['number']);

                // 添加记录
                Db::name('integral_record')->insert(
                    [
                        'member_id'   => Session::get('member_id'),
                        'type_id'     => '2',
                        'type'        => '兑换',
                        'integral'    => $integral['price'],
                        'title'       => '兑换' . $data['title'],
                        'create_time' => time()
                    ]
                );

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '兑换成功'];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }
    }

    /*
     * 积分规则(纯展示页)
     */
    public function integral_rule()
    {
        return $this->fetch('');
    }

    /*
     * 赚取积分
     */
    public function get_integral()
    {
        $rule = (new Config)->where(['vargroup' => 9])->field('varinfo,varvalue,varname')->select();

        foreach ($rule as &$value) {
            if ($value['varname'] == 'web_deduction_percentage') {
                $value['varvalue'] = $value['varvalue'] . "%";
            } elseif ($value['varname'] == 'web_sign') {
                $value['varvalue'] = "7天周期，翻倍得积分";
            }
        }

        // 查看是否签到
        $sign = (new MemberSign)->where(['member_id' => Session::get('member_id'),'sign_time' => date('Y-m-d',time())])->value('id');

        return $this->fetch('', [
            'data' => $rule,
            'sign' => $sign
        ]);
    }

    /*
     * 我的分销(已屏蔽)
     */
    public function my_distribution()
    {
        return $this->fetch('');
    }

    /*
     * 我的钱包->周周币->分销商
     */
    public function distribution_partner(Request $request)
    {
        $id = Session::get('member_id');   //会员id(分销人)
        $type = $request->param('type', '1');   //是否产生佣金(1已产生 2未产生)
        $model = new MemberDistribution();
        $level = MemberDistribution::where('referrals_id', $id)->value('level');   //查找此会员的级别定位
        $type = 2;  //暂改(显示全部,佣金排序)
        if (Session::get('member_id') == 6524) {
            $level = 1;
        }   //老板登录
        $rank = ['one_level' => 0, 'two_level' => 0];

        $data = $model//所有下级分销商
        ->where([
            'sun_member_distribution.level'     => ['elt', ($level + 2)],  //[下两级]
            'sun_member_distribution.hierarchy' => ['like', '%,' . Session::get('member_id') . ',%']
        ])
            ->with([
                'member',
                'memberDistributionOrder' => function ($e) {
                    $e
                        ->where(['distribution_id' => Session::get('member_id')]);
                },
            ])
            ->order(['create_time' => 'desc'])
            ->select();

        if ($data) {
            switch ($type) {
                case 1 : //已产生佣金
                    //去除没有会员信息和分销订单的数据
                    foreach ($data as $key => &$item) {
                        if (!$item->member || !$item->memberDistributionOrder) {
                            unset($data[$key]);
                        } else {
                            foreach ($item->memberDistributionOrder as $o) {
                                $o->memberOrder;    //分销订单关联会员已产生佣金的订单
                            }
                            $flag = 0;
                            foreach ($item->memberDistributionOrder as $_key => $_item) {
                                if (!is_null($_item->memberOrder)) {
                                    $flag = 1;
                                }
                            }
                            if (!$flag) {
                                unset($data[$key]);
                            }   //如果关联的会员已产生佣金的订单全部没有则删除此数据
                        }
                    }
                    foreach ($data as $key => $v) {
                        if ($v->level == ($level + 1)) {  //一级会员数量
                            $rank['one_level'] += 1;
                        } elseif ($v->level == ($level + 2)) {
                            $rank['two_level'] += 1;    //二级会员数量
                        }
                    }
                    break;
                case 2 : //未产生佣金  [暂改]
                    //去除没有会员信息和分销订单的数据
                    foreach ($data as $key => &$item) {
                        if (!$item->member) {
                            unset($data[$key]);
                        } else {
                            foreach ($item->memberDistributionOrder as $o) {
                                $o->memberOrderNot;    //分销订单关联会员所有订单
                            }
                            //                            $flag = 0;
                            //                            foreach ($item->memberDistributionOrder as $_key => $_item){
                            //                                if (!is_null($_item->memberOrderNot)){
                            //                                    if ($_item->memberOrderNot->status > 2){
                            //                                        $flag = 1;
                            //                                    }
                            //                                }
                            //                            }
                            //                            if ($flag){ unset($data[$key]);}  //关联的所有订单状态只要出现大于2的订单则删除
                        }
                    }
                    foreach ($data as $key => $v) {
                        if ($v->level == ($level + 1)) {  //一级会员数量
                            $rank['one_level'] += 1;
                        } elseif ($v->level == ($level + 2)) {
                            $rank['two_level'] += 1;    //二级会员数量
                        }
                    }
                    break;
            }
        }
        if ($request->isPost()) {
            $level_float = $request->post('level');   //等级浮动的值
            $page = $request->post('page');
            //取出对应等级的数据
            $new_data = [];
            if ($data) {
                foreach ($data as &$value) {
                    //关联会员推荐人
                    $value->TjMember;
                    if ($value->level == ($level + $level_float)) {
                        $new_data[] = $value;
                    }
                }
            }

            $result['pages'] = ceil(count($new_data) / 10);
            //            $data_piece = array_slice($new_data,($page - 1)*10, 10);
            $data_piece = $new_data;  //暂改(显示全部,佣金排序)
            $data['data'] = [];
            if ($data_piece) {
                foreach ($data_piece as $key => $item) {
                    $result['data'][$key]['id'] = $item->member->id; //会员id
                    $result['data'][$key]['avatar'] = $item->member->avatar; //会员头像
                    $result['data'][$key]['nickname'] = $item->member->nickname; //会员昵称
                    $result['data'][$key]['username'] = $item->member->username; //会员手机号
                    $result['data'][$key]['TjNickname'] = $item->TjMember->nickname; //推荐人昵称
                    $result['data'][$key]['create_time'] = $item->create_time; //推荐注册时间
                    $result['data'][$key]['brokerage'] = '0.00'; //分销会员佣金

                    if ($item->memberDistributionOrder) {
                        foreach ($item->memberDistributionOrder as $b) {
                            if ($b->memberOrder) {   //关联的是否是已产生佣金的订单
                                if (!is_null($b->memberOrder)) {
                                    $result['data'][$key]['brokerage'] = bcadd($result['data'][$key]['brokerage'], $b->brokerage, 2);
                                }
                            }
                        }
                    }
                }
            }
            //暂改(显示全部,佣金排序)-------佣金排序开始

            if (!empty($result['data'])) {
                $opt1 = [];
                $opt2 = [];
                foreach ($result['data'] as $k => $v) {
                    $opt1[$k] = $v['brokerage'];
                }
                arsort($opt1); //从低到高不改变键值排序
                foreach ($opt1 as $k => $v) {
                    $opt2['data'][] = $result['data'][$k];
                }
                $opt2['pages'] = $result['pages'];
                return $opt2;
            }

            //暂改(显示全部,佣金排序)-------佣金排序结束
        }

        return $this->fetch('', [
            'rank' => $rank,
        ]);
    }

    /*
     * 周周币(佣金)->分销订单
     */
    public function distribution_order(Request $request)
    {
        $model = new MemberDistribution();
        $id = Session::get('member_id');

        $level = MemberDistribution::where('referrals_id', $id)->value('level');   //查找此会员的级别定位
        if ($request->isPost()) {
            $member_id = $request->param('member_id', 0);   //查询所有的下级分销
            $page = $request->post('page');
            $condition = [
                'sun_member_distribution.hierarchy' => ['like', '%,' . $id . ',%']
            ];
            if ($member_id) {   //针对个人查询 (但订单推荐人是当前会员)
                $condition = [
                    'sun_member_distribution.referrals_id' => $member_id
                ];
            }
            $data = $model
                ->where($condition)
                ->where([
                    'sun_member_distribution.level' => ['elt', ($level + 2)],
                ])
                ->with([
                    'member',
                    'memberDistributionOrder' => function ($e) {
                        $e
                            ->where('distribution_id', Session::get('member_id'));  //分销订单上级会员id是当前会员
                    }
                ])
                ->order(['create_time' => 'desc'])
                ->select();

            if ($data) {
                //去除没有会员信息和分销订单的数据
                foreach ($data as $key => &$item) {
                    if (!$item->member || !$item->memberDistributionOrder) {
                        unset($data[$key]);
                    } else {
                        foreach ($item->memberDistributionOrder as $o) {
                            $o->memberOrder;    //分销订单关联会员已产生佣金的订单  [状态为3,4的订单]
                        }
                        $flag = 0;
                        foreach ($item->memberDistributionOrder as $_key => $_item) {
                            if (!is_null($_item->memberOrder)) {
                                $flag = 1;
                            }
                        }
                        if (!$flag) {
                            unset($data[$key]);
                        }   //如果关联的会员已产生佣金的订单全部没有则删除此数据
                    }
                }
            }

            $result['pages'] = ceil(count($data) / 5);

            //截取一段有效数据
            $new_data = array_slice($data, ($page - 5) * 5, 5);
            //            return json($new_data);
            if ($new_data) {
                $opt = [];
                foreach ($new_data as $key => &$item) {
                    $opt[$key]['nickname'] = $item->member->nickname;   //会员昵称
                    $opt[$key]['total_brokerage'] = '0.00';   //会员总佣金初始化
                    if ($item->member_distribution_order) {
                        foreach ($item->member_distribution_order as $k => $_item) {
                            if (!is_null($_item->memberOrder)) {   //没关联上的不取
                                $opt[$key]['list'][$k]['order_time'] = $_item->create_time;   //订单生成时间
                                $opt[$key]['list'][$k]['pay_time'] = date('Y-m-d', $_item->memberOrder->pay_time);   //订单生成时间
                                $opt[$key]['list'][$k]['price'] = $_item->memberOrder->price;   //订单金额
                                $opt[$key]['list'][$k]['brokerage'] = $_item->brokerage;   //产生佣金
                                $opt[$key]['total_brokerage'] = bcadd($opt[$key]['total_brokerage'], $_item->brokerage, 2);
                            }
                        }
                    }
                }

                $opt = array_map(function ($s) {
                    $s['list'] = array_values($s['list']);
                    return $s;
                }, $opt);
                $result['data'] = $opt;
            }
            return $result;
        }
        return $this->fetch();
    }

    /*
     * (主页)消息中心
     */
    public function message_index(Request $request)
    {
        $model = new MemberMessage();
        $user_id = Session::get('member_id');
        $create_time = Db::name('member')->where('id', $user_id)->value('create_time');
        $cc_time = date('Y-m-d H:i:s', $create_time);
        $str = $user_id . ',' . '0';
        $condition['member_id'] = ['in', $str];
        $condition['create_time'] = ['gt', $cc_time];
        if ($request->isPost()) {
            $page = $request->post('page');

            $data['data'] = $model->where($condition)
                ->field('id,title,content,create_time')
                ->order('create_time desc')
                ->limit(($page - 1) * 20, 20)
                ->select();
            $data['pages'] = ceil($model
                    ->where($condition)
                    ->count() / 20);
            return $data;
        }
        //用户消息数量
        $count = $model->where($condition)->count();
        return $this->fetch('', [
            'count' => $count,
        ]);
    }


    // 消息详情
    public function message_details($id)
    {
        if (!$id) throw new Exception('异常操作');
        $content = (new MemberMessage())->where('id', $id)->field('content,title')->find();


        return $this->fetch('', [
            'content' => $content,
        ]);
    }

    /*
     *VIP页面
     */
    public function is_vip()
    {
        // 获取会员ID
        $member_id = Session::get('member_id');

        $info = (new Member())->where('id', $member_id)->find();


        return $this->fetch('', [
            'info' => $info
        ]);
    }


    /*
     * 充值成为VIP
     */
    public function recharge_vip()
    {

        $info = (new Member)->where('id', Session::get('member_id'))->field('username,wechat_id')->find();

        //查询订单总价
        $total = 1;

        //生成订单号
        $order_number = $this->createNumber();
        $information = "vip|" . Session::get('member_id');
        //微信配置参数
        if (self::is_weixin()) {
            $param = (new Wxpay())->check_vip($order_number, $total);
            $is_weixin = 1;
        } else {
            $param = '{}';
            $is_weixin = 2;
        }


        return $this->fetch('', [
            'info'         => $info,
            'param'        => $param,
            'amount'       => $total,
            'is_weixin'    => $is_weixin,
            'order_number' => $order_number,
            'information'  => $information
        ]);
    }


    public function is_weixin()
    {

        if (strpos($_SERVER['HTTP_USER_AGENT'],

                'MicroMessenger') !== false
        ) {

            return true;

        }

        return false;

    }


    protected function checkLogin()
    {
        if (false === Session::has('member_id')) {
            $this->redirect(Url::build('user_port/login'));
        }
    }
}   